package com.yjd.comm.system.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.ReflectionUtils;

import com.yjd.comm.base.model.Model;

/**
 * <b>description</b>：枚举属性填充器 <br>
 * <b>time</b>：2014-8-22 下午7:14:54 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class DictFieldUtil {

	/**
	 * 填充model中的字典属性
	 * 
	 * @param model
	 * @param dictProperty
	 *            需要填充的字典属性列表
	 */
	public static void disposeModel(final Model model,
			List<DictFieldModel> dictPropertys) {
		if (model != null && dictPropertys != null && dictPropertys.size() >= 1) {
			final Map<Object, DictFieldModel> dictProMap = new HashMap<Object, DictFieldModel>();
			for (DictFieldModel dictFieldModel : dictPropertys) {
				dictProMap.put(dictFieldModel.getFieldName(), dictFieldModel);
			}
			if (model != null) {
				ReflectionUtils.doWithFields(model.getClass(),
						new ReflectionUtils.FieldCallback() {
							public void doWith(Field field) {
								if (dictProMap.containsKey(field.getName())) {
									try {
										DictFieldModel dictFieldModel = dictProMap
												.get(field.getName());
										ReflectionUtils.makeAccessible(field);
										if (model.getStrMap() == null) {
											model.setStrMap(new LinkedHashMap<String, Object>());
										}
										model.getStrMap()
												.put(field.getName(),
														DictUtil.getDictDescByCode(
																dictFieldModel
																		.getDictTypeEnum(),
																field.get(model)));
									} catch (Exception e) {
									}
								}
							}
						});
			}
		}
	}

	/**
	 * 填充models中的字典属性
	 * 
	 * @param models
	 * @param dictFields
	 *            需要填充的字典属性列表
	 */
	public static <T extends Model> void disposeModels(List<T> models,
			List<DictFieldModel> dictFields) {
		if (models != null && dictFields != null && dictFields.size() >= 1) {
			for (Model model : models) {
				disposeModel(model, dictFields);
			}
		}
	}

}
